import * as SecureStore from "expo-secure-store";

// Token存储的键
const tokenStoreKey = "authToken";
// RefreshToken存储的键
const refreshTokenStoreKet = "refreshToken";

/**
 * Token管理类
 * @author FlanChan
 */
class TokenManager {
  private token: string | null = null;
  private refreshToken: string | null = null;

  /**
   * 构造函数：当对象初始化时自动获取本地中的token
   */
  constructor() {
    this.token = SecureStore.getItem(tokenStoreKey);
    this.refreshToken = SecureStore.getItem(refreshTokenStoreKet);
  }

  /**
   * 设置token
   * @param token JWT
   */
  setToken(token: string): void {
    SecureStore.setItem(tokenStoreKey, token);
    this.token = token;
  }

  /**
   * 设置refreshToken
   * @param refreshToken
   */
  setRefreshToken(refreshToken: string): void {
    SecureStore.setItem(tokenStoreKey, refreshToken);
    this.refreshToken = refreshToken;
  }

  /**
   * 获取token
   */
  getToken(): string | null {
    return this.token;
  }

  /**
   * 获取refreshToken
   */
  getRefreshToken(): string | null {
    return this.refreshToken;
  }

  /**
   * 清除token
   */
  async clearToken(): Promise<void> {
    this.token = null;
    await SecureStore.deleteItemAsync(tokenStoreKey);
  }

  /**
   * 清除refreshToken
   */
  async clearRefreshToken(): Promise<void> {
    this.refreshToken = null;
    await SecureStore.deleteItemAsync(refreshTokenStoreKet);
  }
}

// 返回一个TokenManager实例以供使用
export default new TokenManager();
